const app = getApp()
const config = require("./config")

const validateUser = (openid, code) => {
  return new Promise((resolve,reject) => {
    const User = new wx.BaaS.TableObject('user');
    const query = new wx.BaaS.Query();
    
    query.compare('openid', '=', openid);
    query.compare('code', '=', code);

    User.setQuery(query).find().then(res => {
      console.log('查询结果', res.data.objects);
      if (res.data.objects.length > 0) {
        resolve(1)
      } else {
        resolve(0)
      }
    }, err => {
      console.error('查询失败', err);
      resolve(-1)
    });
  })
}

const http = (options) =>{
  const data = options.data || {};
  
  return new Promise((resolve,reject) => {
    wx.request({
      url: config.website + options.url,
      method:options.method || 'get',
      data:data,
      header: options.header || {
        'content-type':'application/json'
      },
      success:resolve,
      fail:reject
    })
  })
}

const loginUser = (params) => {
  return http({
    url: '/animal/login',
    method: 'post',
    data: params
  })
}

const getCardNo = (params) => {
  return http({
    url: '/animal/getCardNo',
    method: 'post',
    data: params
  })
}

const addCard = (params) => {
  return http({
    url: '/animal/addCard',
    method: 'post',
    data: params
  })
}

const runAction = (params) => {
  return http({
    url: '/animal/action',
    method: 'post',
    data: params
  })
}

module.exports = {
  loginUser,
  getCardNo,
  addCard,
  runAction,
  validateUser
}
